class WxRequest {
  defaults = {
    baseUrl: '',
    url: '',
    data: null,
    method: 'GET',
    header: {
      'Content-type': 'application/json'
    },
    timeout: 60000,
    isLoading: true
  }
  //请求队列
  queue = []
  //定义拦截器对象
  interceptors = {
    request: (config) => config,
    response: (response) => response
  }
  constructor(params = {}) {
    this.defaults = { ...this.defaults, ...params }
  }
  request(options) {
    this.timerId && clearTimeout(this.timerId)
    options.url = this.defaults.baseUrl + options.url
    options = { ...this.defaults, ...options }
    options = this.interceptors.request(options)
    //并发的第一个请求
    if (options.isLoading && options.method !== 'UPLOAD') {
      if (this.queue.length === 0) {
        wx.showLoading({
          title: '数据加载中...'
        })
      }
      this.queue.push('request')
    }
    return new Promise((resolve, reject) => {
      if (options.method === 'UPLOAD') {
        wx.uploadFile({
          ...options,
          success: (res) => {
            console.log(options)
            res.data = JSON.parse(res.data)
            const mergeRes = { ...res, config: options, isSuccess: true }
            resolve(this.interceptors.response(mergeRes))
          },
          fail: (err) => {
            res.data = JSON.parse(res.data)
            const mergeErr = { ...err, config: options, isSuccess: false }
            resolve(this.interceptors.response(mergeErr))
          }
        })
      } else {
        wx.request({
          ...options,
          success: (res) => {
            const mergeRes = { config: options, ...res, isSuccess: true }
            resolve(this.interceptors.response(mergeRes))
          },
          fail: (err) => {
            const mergeErr = { config: options, ...err, isSuccess: false }
            reject(this.interceptors.response(mergeErr))
          },
          complete: () => {
            if (options.isLoading) {
              //完成最后一个请求
              this.queue.pop()
              //并发请求结束
              this.queue.length === 0 && this.queue.push('request')
              //利用定时器解决闪烁
              this.timerId = setTimeout(() => {
                this.queue.pop()
                wx.hideLoading()
                clearTimeout(this.timerId)
              }, 1)
            }
          }
        })
      }
    })
  }
  get(url, data = {}, config = {}) {
    return this.request({ url, data, method: 'GET', ...config })
  }
  delete(url, data = {}, config = {}) {
    return this.request({ url, data, method: 'DELETE', ...config })
  }
  post(url, data = {}, config = {}) {
    return this.request({ url, data, method: 'POST', ...config })
  }
  put(url, data = {}, config = {}) {
    return this.request({ url, data, method: 'PUT', ...config })
  }
  all(...promise) {
    return Promise.all(promise)
  }
  upload(url, filePath, name = 'file', config = {}) {
    return this.request({ url, filePath, name, method: 'UPLOAD', ...config })
  }
}
export default WxRequest
